import {ChangeDetectorRef, Component, NgZone, ViewChild} from '@angular/core';

import {
    IonicPage,
    NavController,
    NavParams,
    DateTime,
    ToastController,
    ActionSheetController,
    Platform
} from 'ionic-angular';
import * as moment from 'moment';

import {ClientMod} from '../../../model/pages/client/clients-add/clients-add.model';
import {ClientAddProvider} from '../../../providers/client/client-add/client-add.provider';
import {Keyboard} from "ionic-angular"
import {MessageBushService} from "../../../services/common/message-bush.service";
import {AlertController, Select} from 'ionic-angular';
import {Content} from 'ionic-angular';
import {LoadingService} from "../../../services/common/loading.service";
import {ClientMapProvider} from "../../../providers/client/client-map/client-map.provider";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";
import $ from 'jquery';

@IonicPage()
@Component({
    selector: 'page-client-add',
    templateUrl: 'client-add.html',
    providers: [
        ClientAddProvider,
        LoadingService,
        ClientMapProvider
    ]
})
export class ClientsAddPage {


    //表单验证提示信息
    public FormTip = {
        name: "请填写客户姓名",
        phone: "请填写正确的电话",
        postCode: "请填写正确的邮编",
        otherIns: "请选择保险类型",
        income: "请输入正确的工资",
        addressTip: "地址不能为空"
    };

    @ViewChild(Content) content: Content;

    @ViewChild("select1") select1: Select;
    @ViewChild("select2") select2: Select;
    @ViewChild("select3") select3: Select;
    @ViewChild("select4") select4: Select;
    @ViewChild("select5") select5: Select;
    @ViewChild("select6") select6: Select;
    // picker当前最大时间节点
    private maxDate: string = moment(new Date()).format('YYYY-MM-DD');


    // 客户界面model总信息
    private clientsModel: ClientMod = new ClientMod();

    // 传参 model 信息
    private clientsParamsModel: ClientMod = new ClientMod();
    //日期选择器配置
    private pickerOptions = {
        cssClass: 'client-add-picker'
    };
    // input ReadOnly
    public readonly = true;
    // 展开更多
    public isOpen: boolean = false;
    public testPhone: RegExp = /^[0-9]*$/;
    public testName: RegExp = /^[a-zA-Z\u4e00-\u9fa5\·\ \s]{1,20}$/;
    public isDisabled = false;
    public jobKind = [
        "一般职业",
        "一般商业",
        "制造业",
        "农牧业",
        "渔业",
        "木材、森林业",
        "木材加工业",
        "矿石、采石业",
        "交通运输业",
        "餐旅业",
        "建筑工程业",
        "服务业",
        "家庭管理",
        "治安人员",
        "军人",
        "咨讯业",
        "职业运动人员",
        "新闻广告业",
        "卫生、保健业",
        "娱乐业",
        "文教机关",
        "司法",
        "宗教团体",
        "公共事业",
        "其他"
    ];
    public clientData;
    public clientHeight;
    public clientDataNew; //新增带有姓名电话的准客户、

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public toastCtrl: ToastController,
                private ref: ChangeDetectorRef,
                public cliAddPro: ClientAddProvider,
                public keyboard: Keyboard,
                public alert: AlertController,
                public actionSheetCtrl: ActionSheetController,
                public platform: Platform,
                public zone: NgZone,
                public load: LoadingService,
                public  map: ClientMapProvider,
                public adpActionSheet: AdpActionSheetController) {
        this.clientHeight = document.body.clientHeight;
    }


    ionViewDidLoad() {
        this.editClientsData();
        this.showSex();
        this.scrollHeight = $('.scroll-content')[$('.scroll-content').length - 1].scrollTop;
    }

    ionViewDidEnter() {
    }

    ionViewWillLeave() {
        this.select1.close();
        this.select2.close();
        this.select3.close();
        this.select4.close();
        this.select5.close();
        this.select6.close();
    }

    public scrollHeight = 0;

    /**
     *  滚动失光标
     */
    onScroll() {
        this.scrollHeight = $('.scroll-content')[$('.scroll-content').length - 1].scrollTop;
    }

    height;
    contentHeight;
    private maxDateYear = Number(moment(new Date()).format('YYYY'));

    /**
     * 向datatpicker添加年度顺序排列数据：[2010,2011,2012...2100]
     */
    getYearList(start: number, end: number = this.maxDateYear) {

        let years = [];
        if (typeof start == 'number' && typeof end == 'number' && start && end) {
            for (let y = start; y <= end; y++) {
                years.push(y)
            }
        } else {
            for (let y = start; y <= end; y++) {
                years.push(y)
            }
        }
        return years
    }

    /**
     * 获取元素高度
     * @param e
     * @returns {any}
     */
    getTop(e) {
        let offset = e.offsetTop;
        if (e.offsetParent != null) offset += this.getTop(e.offsetParent);
        return offset;
    }

    /**
     * input获得焦点
     * @param ele
     * @param ev
     */
    inputFocus(ev) {

        ev.stopPropagation();
        ev.preventDefault();
        // 当前屏幕高度..
        this.contentHeight = document.body.clientHeight;

        if ($(ev.target).offset().top > this.contentHeight / 2) {
            this.content.scrollTo(0, $(ev.target.offsetParent).offset().top +
                this.scrollHeight - 200, 500);
        }
        console.log($(ev.target).offset().top)
    }

    /**
     *  初始化界面。新增，编辑
     */
    editClientsData() {
        this.clientData = this.navParams.get("data");
        let addData = this.navParams.get('addData');
        if (this.clientData) {
            this.clientsModel = JSON.parse(JSON.stringify(this.navParams.get('data')));
            if (this.clientsModel.mobileList && this.clientsModel.mobileList.length == 0) {
                this.clientsModel.mobileList = [{mobile: '', id: '', defaultIndicator: "", isDel: false}];
            }
            if (this.clientsModel.addressList && this.clientsModel.addressList.length == 0) {
                this.clientsModel.addressList = [{
                    address: '',
                    defaultIndicator: "1",
                    id: "",
                    locationLatitude: "",
                    locationLongitude: "",
                    postCode: "",
                    isDel: false
                }];
            }
            if (this.clientsModel.income) {
                this.clientsModel.income = Number(this.clientsModel.income).toFixed();
            }
        } else {
            if (addData) {
                this.clientsModel.name = addData.name;
                this.clientsModel.mobileList = [{mobile: addData.tel, id: '', defaultIndicator: "", isDel: false}];
                this.clientsModel.addressList = [{
                    address: '',
                    defaultIndicator: "1",
                    id: "",
                    locationLatitude: "",
                    locationLongitude: "",
                    postCode: "",
                    isDel: false
                }];
            } else {
                this.clientsModel.mobileList = [{mobile: '', id: '', defaultIndicator: "", isDel: false}];
                this.clientsModel.addressList = [{
                    address: '',
                    defaultIndicator: "1",
                    id: "",
                    locationLatitude: "",
                    locationLongitude: "",
                    postCode: "",
                    isDel: false
                }];
            }
        }
    }

    /**
     * 选择是否在其他公司购买保险
     */
    otherSelectChoose() {
        if (this.clientsModel.otherIns == "2") {
            this.clientsModel.insType = "";
        }
    }

    /**
     * 购买保险类型多选
     */
    otherType(ind){
        console.log(ind)
    }

    /**
     * 性别选择
     */
    chooseSex() {
        let actionSheet = this.adpActionSheet.create({
            title: '性别',
            buttons: [
                {
                    text: '男',
                    role: 'destructive',
                    cssClass: this.clientsModel.sex == "男" ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.clientsModel.sex = "男";
                    }
                }, {
                    text: '女',
                    cssClass: this.clientsModel.sex == "女" ? 'action-sheet-selected' : '',
                    handler: () => {
                        this.clientsModel.sex = "女";
                    }
                }, {
                    text: '取消',
                    role: 'cancel',
                    handler: () => {
                        console.log('Cancel clicked');
                    }
                }
            ]
        });
        actionSheet.present();
    }

    /**
     * 选择职业
     */
    chooseOccupation() {
        let jobArray = [];
        this.jobKind.forEach((m) => {
            let obj = {};
            obj['text'] = m;
            obj['cssClass'] = this.clientsModel.occupation == m ? 'action-sheet-selected' : '';
            obj['handler'] = () => {
                this.clientsModel.occupation = m;
            };
            jobArray.push(obj);
        });
        this.adpActionSheet.create({
            title: '职业',
            buttons: jobArray,
            cssClass: 'mySelect'
        }).present();
    }

    /**
     * 初始化页面显示性别
     */
    showSex() {
        if (this.clientsModel.sex && this.clientsModel.sex == 'M') {
            this.clientsModel.sex = "男";
        }
        if (this.clientsModel.sex && this.clientsModel.sex == 'F') {
            this.clientsModel.sex = "女";
        }
        if (!this.clientsModel.sex) {
            this.clientsModel.sex = "请选择";
        }
        if (!this.clientsModel.occupation) {
            this.clientsModel.occupation = "请选择";
        }
    }

    /**
     * 添加新手机
     */
    addNewPhone(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.clientsModel.mobileList.push({mobile: '', id: "", defaultIndicator: "", isDel: false});
        this.ref.detectChanges();
    }

    /**
     * 输入电话号码
     */
    inputOnchange(i, ev) {
        let val = ev.value.replace(/[^0-9]/ig, '');
        // if (val.length > 1) {
        //     //当大于1位数的时候，去掉第一个0
        //     val = val.replace(/^[0]+/, '');
        // }
        ev.value = val;
        this.clientsModel.mobileList[i].mobile = val;
    }

    /**
     * 删除界面手机
     */
    delLocalPhone(ind, ev, data, isEmpty) {
        ev.preventDefault();
        ev.stopPropagation();
        if (isEmpty) {
            data.mobileList.splice(ind, 1);
        } else {
            this.clientsModel.mobileList.splice(ind, 1);
        }
        this.ref.detectChanges();
    }

    /**
     * 添加新地址
     */
    addNewAddress(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.clientsModel.addressList.push({
            address: '',
            defaultIndicator: "0",
            id: "",
            locationLatitude: "",
            locationLongitude: "",
            postCode: "",
            isDel: false
        });
        if (this.clientsModel.addressList.length === 1) {
            this.clientsModel.addressList[0].defaultIndicator = '1';
        }
        this.ref.detectChanges()
    }


    /**
     * 地址输入框失去焦点
     */
    inputBlur(i) {
        this.clientsModel.addressList[i].address = this.clientsModel.addressList[i].address.toUpperCase();
    }

    /**
     * 输入邮编
     */
    inputOnchangePostCode(i, ev) {
        let val = ev.target.value.replace(/[^0-9]/ig, '');
        if (ev.target.value.length > 1) {
            //当大于1位数的时候，去掉第一个0
            val = val.replace(/^[0]+/, '');
        }
        ev.target.value = val;
        this.clientsModel.addressList[i].postCode = val;
    }

    /**
     * 删除地址
     */
    delLocalAddress(ind, ev, data) {

        ev.preventDefault();
        ev.stopPropagation();
        let add = this.clientsModel.addressList;
        if (add.length && Number(add[ind].defaultIndicator)) {
            add[0].defaultIndicator = "1";
        }
        add.splice(ind, 1);
        this.ref.detectChanges();
    }

    /**
     * 输入月薪
     */
    inputOnchangeSalary(i, ele, ev) {
        // let incomePatrn: RegExp = /^[0-9.]*$/;
        // if (ev.value && !incomePatrn.test(ele.value)) {
        //     this.toast("月薪只能为数字", 'middle');
        // }
        //替换除了数字的所有字符


        let val = ev.value.replace(/[^0-9]/ig, '');
        if (ev.value.length > 1) {
            //当大于1位数的时候，去掉第一个0
            val = val.replace(/^[0]+/, '');
        }
        ev.value = val;
        this.clientsModel.income = val;
    }


    /**
     * 页面表单验证\提示
     */
    getCheckData(data) {
        const testPhone: RegExp = /^[0-9]*$/;
        const incomePatrn: RegExp = /^[0-9.]*$/;
        let phoneTip: boolean = true;
        let postCodeTip: boolean = true;
        let addressTip: boolean = true;
        data.name = data.name && data.name.trim();
        if (data.mobileList && data.mobileList.length) {
            for (let i = 0; i < data.mobileList.length; i++) {
                if (data.mobileList.length && data.mobileList[i].mobile && testPhone.test(data.mobileList[i].mobile) == false) {
                    phoneTip = false;
                }
            }
        }
        if (data.addressList && data.addressList.length) {
            for (let i = 0; i < data.addressList.length; i++) {
                if (data.addressList[i].postCode && testPhone.test(data.addressList[i].postCode) == false) {
                    postCodeTip = false;
                }
                //有邮编的地址不能为空
                if (!data.addressList[i].address && data.addressList[i].postCode) {
                    addressTip = false;
                }
            }
        }


        if (!data.name) {
            this.toast(this.FormTip.name, "bottom");
            return false;
        } else if (!this.testName.test(data.name)) {
            this.toast("姓名仅支持汉字或英文字母", "bottom");
            return false;
        } else if (phoneTip == false) {
            this.toast(this.FormTip.phone, "bottom");
            return false;
        } else if (postCodeTip == false) {
            this.toast(this.FormTip.postCode, "bottom");
            return false;
        } else if (addressTip == false) {
            this.toast(this.FormTip.addressTip, 'bottom');
            return false;
        } else if (data.otherIns == 1 && !data.insType) {
            this.toast(this.FormTip.otherIns, "bottom");
            return false;
        } else if (!incomePatrn.test(data.income) && data.income) {
            this.toast(this.FormTip.income, "bottom");
            return false;
        } else {
            return true;
        }
    }

    /**
     * 验证电话和姓名
     */
    checkCust(ev) {

        this.isDisabled = true;
        this.clientsParamsModel = JSON.parse(JSON.stringify(this.clientsModel));
        let par = this.clientsParamsModel;
        if (!this.getCheckData(this.clientsModel)) {
            this.isDisabled = false;
            return;
        }

        let mobileList2 = [];
        for (let i = 0; i < par.mobileList.length; i++) {
            // push有号码的电话
            if (par.mobileList[i].mobile && !par.mobileList[i].defaultIndicator) {
                mobileList2.push(par.mobileList[i]);
            }
        }
        par.mobileList = mobileList2;
        let data = {
            "name": par.name,
            "mobileList": par.mobileList,
            "userId": ''
        };
        if (this.clientData) {
            data.userId = this.clientData.leadId;
        }
        this.load.showLoading();
        this.cliAddPro.checkCustomer(data).subscribe(res => {
            this.addProCust(ev);
            MessageBushService.setMessage(MessageBushService.keys.favoriteIsUpdated, '1');
        }, (error) => {
            this.load.dismissLoading();
            this.isDisabled = false;
            if (error.status == 500) {
                if (JSON.parse(error.error).status == 999) {
                    if (JSON.parse(error.error).exception == "Prospect already exist") {
                        this.toast("当前客户已存在", "bottom");
                        this.isDisabled = false;
                    } else if (JSON.parse(error.error).exception == "Mobile already exist") {
                        this.alert.create({
                            title: '电话已经存在',
                            message: '当前电话已存在，是否继续添加为准客户？',
                            cssClass:'ifAddCust',
                            buttons: [{
                                text: '取消', handler: () => {
                                    this.isDisabled = false;
                                }
                            }, {
                                text: '确定', handler: () => {
                                    this.isDisabled = true;
                                    this.addProCust(ev, 1);
                                }
                            }]
                        }).present();
                    }
                } else {
                    this.isDisabled = false;
                }
            }
        })
    }

    /**
     * 处理参数
     */
    checkParamsModel(ev) {
        let c = this.clientsParamsModel;
        let addressList2 = [];
        for (let i = 0; i < c.addressList.length; i++) {
            if (c.addressList[i].address) {
                addressList2.push(c.addressList[i]);
            }
        }
        c.addressList = addressList2;
        let ddd = [];
        for (let j = 0; j < c.addressList.length; j++) {
            ddd.push(c.addressList[j].defaultIndicator);
        }
        if (c.addressList[0] && ddd.indexOf("1") == -1) {
            c.addressList[0].defaultIndicator = "1";
        }
        if (c.sex == "请选择") {
            c.sex = '';
        } else if (c.sex == "男") {
            c.sex = "M"
        } else if (c.sex == "女") {
            c.sex = "F";
        }
        if (this.clientData) {
            c.partyId = this.clientData.partyId;
        }
        if (!this.clientData) {
            c.source = "手工添加";
        }
        if (c.occupation == '请选择') {
            c.occupation = null;
        }
        return c;
    }

    /**
     * 创建准客户
     */


    addProCust(ev, loading = 0) {
        if (loading) {
            this.load.showLoading();
        }
        this.cliAddPro.addNewCustomer(this.checkParamsModel(ev)).subscribe(res => {
            this.load.dismissLoading();
            this.toast("保存成功", "bottom");
            if (this.clientsParamsModel.addressList && this.clientsParamsModel.addressList.length) {
                for (let i = 0; i < this.clientsParamsModel.addressList.length; i++) {
                    if (this.clientsParamsModel.addressList[i].defaultIndicator == '1') {
                        this.map.updatePoiByClientId(this.clientsParamsModel.addressList[i].address, res, 1).subscribe(res => {
                        });
                    }
                }
            } else {
                this.map.updatePoiByClientId('', res, 1).subscribe(res => {
                });
            }
            MessageBushService.setMessage(MessageBushService.keys.clientListUpdated, '1');
            MessageBushService.setMessage(MessageBushService.keys.prospectiveClientsUpdated, '1');
            MessageBushService.setMessage(MessageBushService.keys.clientDetailDataUpdated, '1');
            MessageBushService.setMessage(MessageBushService.keys.clientMapCustomerDetailUpdated, '1');
            this.isDisabled = false;
            this.backToProPage();
        }, (error) => {
            this.load.dismissLoading();
            this.isDisabled = false;
        });
    }

    /**
     *  toast 提示信息
     * @param {string} message 提示内容
     * @param {string} position 显示位置
     */
    toast(message: string, position: string) {
        this.toastCtrl.create({
            message: message,
            position: 'middle',
            duration: 1500
        }).present();
    }

    /**
     *  返回
     */
    backToProPage() {
        this.navCtrl.pop(null);
    }

    /**
     * 设置默认地址
     */
    setDefaultAddress(index, isDefault) {
        console.log(123)
        let def = this.clientsModel.addressList;
        if (isDefault == 1) return;
        for (let a = 0; a < def.length; a++) {
            if (index == a && !Number(def[a].defaultIndicator)) {
                def[a].defaultIndicator = '1';
            } else if (def.length > 1) {
                def[a].defaultIndicator = '0';
            }
        }
    }
}
